#!/usr/bin/env python
# -*- coding: utf-8 -*-

import ipaddress
import ipdb
from app.config.settings import IPV4_DATA, IPV6_DATA


class IpAddressDB(object):

    def __init__(self):
        self.ipv4db = ipdb.City(IPV4_DATA)
        self.ipv6db = ipdb.City(IPV6_DATA)
        self.fields = ['country_name', 'region_name', 'city_name', 'isp_domain']

    def get_address_obj(self, ip, language='CN'):
        try:
            ipv = ipaddress.ip_address(ip)
        except Exception:
            return {}
        if ipv.version == 6:
            db = self.ipv6db
        elif ipv.version == 4:
            if ip.startswith('10.') or ip.startswith('172.') or ip.startswith('127.') or ip.startswith('192.168.'):
                return {}
            db = self.ipv4db
        else:
            return {}
        try:
            ret = db.find_map(ip, language)
        except Exception:
            return {}
        return ret

    def get_address(self, ip, language='CN', fields=None, join_str=''):
        address_obj = self.get_address_obj(ip, language)
        if not address_obj:
            return '未知'
        address_list = [address_obj.get(field, '') for field in (fields if fields else self.fields)]
        return join_str.join(address_list)


IP_ADDRESS_DB = IpAddressDB()


def getip2address(ip, locale='cn'):
    return IP_ADDRESS_DB.get_address(ip, locale.upper())


def getipinfo(ip, locale='cn'):
    address_obj = IP_ADDRESS_DB.get_address_obj(ip, locale.upper())
    if not address_obj:
        return []
    return [
        address_obj.get('country_name', ''),
        address_obj.get('region_name', ''),
        address_obj.get('city_name', ''),
        '',
        address_obj.get('isp_domain', '')
    ]


def get_ip_location(ip, locale='cn', country=True, province=True, city=False, res_type=""):
    ip_info = getipinfo(ip, locale) or []
    if ip_info:
        if res_type == "list":
            location = ip_info
        else:
            location = " ".join([ip_info[index] or "未知" for index, need in enumerate([country, province, city]) if need])
    else:
        location = '未知'
    return location
